package com.lyhengtongwl.zqsnews.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.BuildConfig;
import com.liulishuo.filedownloader.FileDownloadLargeFileListener;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.lyhengtongwl.zqsnews.base.Constant;

import java.io.File;

public class Downloadutils {

    private static final String TAG = "Downloadutils";

    private Context mContext;

    private static Downloadutils instance = new Downloadutils();

    private Downloadutils() {
    }

    public static Downloadutils getInstance() {
        return instance;
    }

    private BaseDownloadTask fileDownloaderTask;

    private void setContext(Context ctx) {
        this.mContext = ctx;
    }

    /**
     * 创建下载
     */
    public void crateFileDownloader(Context mContext, String updateApkUrl) {
        FileDownloader.setup(mContext);
        this.mContext = mContext;
        FileDownloader.getImpl().create(updateApkUrl)
                .setPath(Constant.DIR_INFO.APP_DIR + File.separator + "update/pintuan.apk")
                .setListener(fileDownloader).start();
    }


    /**
     * 下载监听
     */
    private FileDownloadListener fileDownloader = new FileDownloadLargeFileListener() {
        @Override
        protected void pending(BaseDownloadTask task, long soFarBytes, long totalBytes) {
            Log.e(TAG, "pending---已经进入下载队列----总大小：" + (totalBytes / 1024 / 1024) + "-----剩余----" + (soFarBytes / 1024 / 1024) + "M");
            fileDownloaderTask = task;
        }

        @Override
        protected void progress(BaseDownloadTask task, long soFarBytes, long totalBytes) {
            Log.e(TAG, "progress--下载进度回调--总大小：" + (totalBytes / 1024 / 1024) + "-----剩余----" + (soFarBytes / 1024 / 1024) + "M");
            fileDownloaderTask = task;
        }

        @Override
        protected void paused(BaseDownloadTask task, long soFarBytes, long totalBytes) {
            Log.e(TAG, "paused---暂停下载----总大小：" + (totalBytes / 1024 / 1024) + "-----剩余----" + (soFarBytes / 1024 / 1024) + "M");
            fileDownloaderTask = task;

        }

        @Override
        protected void completed(BaseDownloadTask task) {
            Log.e(TAG, "completed------下载完成-----apk路径---" + task.getPath());
            fileDownloaderTask = task;
//            downloadUpdateTvContext.setText("下载完成，保存路径为：" + task.getPath());
            installAPK(task.getPath());

        }

        /**
         * 安装APK
         *
         * @param path
         */
        private void installAPK(String path) {
            File fileApk = new File(path);
            if (!fileApk.exists()) {
                ToastUtil.showShort(mContext, "找不到APK路径");
                return;
            }
            Intent intent = new Intent(Intent.ACTION_VIEW);

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri apkUri = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                apkUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", fileApk);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                apkUri = Uri.fromFile(fileApk);
            }

            intent.setDataAndType(apkUri,
                    "application/vnd.android.package-archive");

            mContext.startActivity(intent);
        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            Log.e(TAG, "error----下载错误---" + e.getMessage());
            fileDownloaderTask = task;
        }

        @Override
        protected void warn(BaseDownloadTask task) {
            Log.e(TAG, "warn----在下载队列中(正在等待/正在下载)已经存在相同下载连接与相同存储路径的任务");
            ToastUtil.showShort(mContext, "已经存在相同下载连接与相同存储路径的任务请清空重新下载");
        }
    };

}
